<template>
  <van-radio-group
    :value="checked"
    :direction="direction"
    class="button-radio-group"
    :class="customClass"
    :style="radioStyle"
    @change="onChange"
  >
    <van-radio
      v-for="(item,index) in items"
      :key="index"
      :name="item.name"
      use-icon-slot
      :custom-class="checked === item.name?'button-radio--active': ''"
    >
      {{item.text}}
    </van-radio>
  </van-radio-group>
</template>

<script>
const CHECKED_COLOR = '#1989fa'
export default {
  props: {
    // 默认选项
    value: {
      type: String,
      default: ''
    },
    // 方向
    direction: {
      type: String,
      default: 'horizontal'
    },
    // 选项数组
    items: {
      type: Array,
      required: true
    },
    // 选中时样式颜色
    checkedColor: {
      type: String,
      default: CHECKED_COLOR
    },
    // 反相
    reverse: {
      type: Boolean,
      default: false
    },
    // 圆角
    round: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      checked: ''
    }
  },
  watch: {
    value (v) {
      this.checked = v
    }
  },
  mounted () {
    console.group('radioButton')
    this.checked = this.value || this.items[0].name
    console.groupEnd('radioButton')
  },
  computed: {
    customClass () {
      let classes = []
      if (this.reverse) {
        classes.push('button-radio--reverse')
      }
      if (this.round) {
        classes.push('button-radio--round')
      }
      return classes.join(' ')
    },
    radioStyle () {
      if (this.checkedColor !== CHECKED_COLOR) {
        return `--radio-checked-color: #${this.checkedColor}`
      }
      return ''
    }
  },
  methods: {
    onChange (e) {
      this.checked = e.mp.detail
      this.notice()
    },
    notice () {
      console.log(this.checked)
      this.$emit('change', this.items.find(item => {
        return item.name === this.checked
      }))
    }
  }
}
</script>

<style lang="less">
.button-radio {
  &-group {
    &:root {
      --radio-checked-color: #1989fa;
    }
    .van-radio {
      &-group--horizontal {
        flex-wrap: nowrap;
      }
      &__label {
        margin: 0;
        border: 1px solid #ebedf0;
        color: #323233;
        background: #fff;
        border-radius: 5px;
        padding: 5px 12px;
        font-size: 14px;
      }
    }
  }
  &--active {
    .van-radio__label {
      background: var(--radio-checked-color);
      border-color: var(--radio-checked-color);
      color: #fff;
    }
  }
  &--round {
    .van-radio__label {
      border-radius: 30px;
    }
  }
  &--reverse {
    .van-radio__label {
      border-color: #fff;
      color: #fff;
      background: transparent;
    }
    .button-radio--active {
      .van-radio__label {
        color: var(--radio-checked-color);
        background: #fff;
      }
    }
  }
}
</style>